/**
 * @Author: jipeng.Li
 * @Date: 2021-02-26 18:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-29 20:02:21
 * @Description: 交易记录
 */
import React, { Component } from 'react';
import { Image, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import {
  fontColorBlack,
  fontColorDeepGray,
  isAndroid,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp
} from '@/styles';
import { BackImageOn, XMHeader, msg } from '@/common';
import {
  empty08,
  iconActivationFlag,
  iconAllOil,
  iconAllOilActivate,
  iconConfigOil,
  iconConfigOilActivate,
  iconConsumeOil,
  iconConsumeOilActivate,
  iconDown,
} from '@/images';
import wlRepair from '@/api/repair';
import tool from '@/common/getDate';
import TransactionsRecordModal from '../oil-card-platform/components/transactions-record-modal';
import XmList from '../../components/XmList';
import EmptyPage from '../../components/EmptyPage';

export default class TradeRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewTitle: '全部',
      optionIndex: 0, // 选项选中
      modalIsShow: false, // 是否显示选择模态框,
      cardData: {},
      pageNo: 1,
      pageSize: 15,
      hasMorePage: true,
      isLoading: false,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      tradeList: [],
    };
  }

  optionSource = [
    { id: 0, text: '全部', icon: iconAllOil, activateIcon: iconAllOilActivate },
    { id: 1, text: '核销', icon: iconConsumeOil, activateIcon: iconConsumeOilActivate },
    { id: 3, text: '法人配维修费', icon: iconConsumeOil, activateIcon: iconConsumeOilActivate },
    { id: 4, text: '法人回收余额', icon: iconConfigOil, activateIcon: iconConfigOilActivate },
    // {id: 4, text: '余额回收', icon: iconConsumeOil, activateIcon: iconConsumeOilActivate},
    // {id: 5, text: '限额分享', icon: iconConsumeOil, activateIcon: iconConsumeOilActivate},
    // {id: 6, text: '分享回收', icon: iconConsumeOil, activateIcon: iconConsumeOilActivate},
  ]

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardData } = params;
    this.setState({ cardData }, () => {
      this.loadData();
    });
  }

  componentWillUnmount() {
    msg.emit('setUpWlRepairQrCodeInterval');
  }

  render() {
    const { optionIndex, modalIsShow, isLoading, hasMorePage, showFoot, tradeList } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        {this.renderHead()}
        <XmList
          sources={tradeList}
          renderItem={this._renderItem}
          style={styles.container}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          hasMorePage={hasMorePage}
          onPullUpMore={this.LoadMore}
          singleKey={item => `tradeList${item.id}`}
          showFoot={showFoot}
          customEmptyView={<EmptyPage emptyIcon={empty08} noText='您暂时还没有交易记录哦~' />}
        />
        {modalIsShow && (
          <TransactionsRecordModal
            activationFlag={iconActivationFlag}
            optionSource={this.optionSource}
            optionIndex={optionIndex}
            optionClick={({ id, text }) => {
              this.setState({ optionIndex: id, viewTitle: text }, () => this.loadData());
            }}
            modalClick={() => this.setState({ modalIsShow: false })}
          />
        )}
      </SafeAreaView>
    );
  }

  // 自定义头部
  renderHead = () => {
    const { modalIsShow, viewTitle } = this.state;
    return (
      <XMHeader
        renderTitle={() => {
          return (
            <TouchableOpacity
              onPress={() => this.setState({ modalIsShow: !modalIsShow })}
              style={styles.headTitleContainer}
            >
              <Text
                style={styles.headTitleText}
              >
                {viewTitle}
              </Text>
              <Image
                style={styles.headTitleImage}
                source={iconDown}
              />
            </TouchableOpacity>
          );
        }}
        renderLeft={() => {
          return (
            <BackImageOnOnOn onClick={() => {
              msg.emit('router: back');
            }}
            />
          );
        }}
      />
    );
  }

  _renderItem = ({ item }) => {
    return (
      <View style={styles.contentItemContainer}>
        <View style={styles.contentItem}>
          <Text
            style={{
              fontSize: px2dp(32),
              color: fontColorBlack,
              fontWeight: 'bold'
            }}
          >
            {this.assembleTitle(item)}
          </Text>
          {this.formatPrice(item.state, item.money)}
        </View>
        <View style={styles.contentItem}>
          <Text style={{ fontSize: px2dp(26), color: '#999793' }}>
            {tool.dateForm(item.createTime, 'yyyy-MM-dd hh:mm:ss')}
          </Text>
          <Text style={{ color: fontColorDeepGray }}>
            {item.balance}
          </Text>
        </View>
      </View>
    );
  }

  assembleTitle = (item) => {
    const { detail, transactionType, verificationName } = item;
    let title = {
      1: `${detail}-${verificationName ? `-${verificationName}` : ''}`,
      3: '法人配维修费',
      4: '法人回收余额',
      // 4: '余额回收',
      // 5: '限额分享',
      // 6: '分享回收',
    };
    return title[transactionType] || detail;
  }

  formatPrice = (flag, price) => {
    if (flag == 2) {
      return (
        <Text style={{ fontSize: px2dp(36), color: '#EB2F2F' }}>{`-${price}`}</Text>
      );
    }
    return (
      <Text style={{ fontSize: px2dp(36), color: '#2CBD26' }}>{`+${price}`}</Text>
    );
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      tradeList: [],
      showFoot: 0
    }, () => {
      this.pageTransaction('dropdown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => this.pageTransaction('pullMore'));
  }

  /**
   * 接口
   */
  pageTransaction = (type) => {
    const { cardData, optionIndex, pageNo, pageSize, tradeList } = this.state;
    const apiName = {
      1: {
        api: 'pageTransaction',
        id: 'accountCarownerId'
      },
      2: {
        api: 'pageDriverTransaction',
        id: 'id'
      },
    };
    let newTradeList = [];
    wlRepair[apiName[cardData.type].api]({
      id: cardData[apiName[cardData.type].id],
      transactionType: optionIndex || '',
      pageNo: pageNo,
      pageSize: pageSize
    }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'dropdown') {
          this.setState({ tradeList: records });
        }
        if (type === 'pullMore') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newTradeList = [...tradeList, ...records];
          this.setState({ tradeList: newTradeList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1, modalIsShow: false });
      } else {
        msg.emit('app:tip', { text: res.msg });
        this.setState({ isLoading: false, pageNo: pageNo + 1, tradeList: [] });
      }
    });
  }
}

const styles = StyleSheet.create({
  headTitleContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  headTitleText: {
    color: '#000',
    fontSize: 18,
    fontWeight: isAndroid ? '400' : 'bold'
  },
  headTitleImage: {
    marginLeft: px2dp(10),
    width: px2dp(20),
    height: px2dp(20)
  },
  contentContainer: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  contentItemContainer: {
    height: px2dp(160),
    justifyContent: 'space-around',
    backgroundColor: mainBgColorWhite,
    borderBottomWidth: px2dp(1),
    borderBottomColor: '#F0EFEF',
    paddingHorizontal: px2dp(25)
  },
  contentItem: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
});
